// 纯前端BFL API集成 - 完整的跨域解决方案
// 更新日期：2025年8月 - 已更新为最新可用的CORS代理服务

// BFL API配置
const BFL_CONFIG = {
  // 直接设置 API 密钥（InfinityFree 不支持环境变量）
  apiKey: import.meta.env.VITE_BFL_API_KEY || '8bca398e-2787-4bc8-84fd-a89cf5e34052',
  timeout: 60000, // 60秒超时

  // PHP 代理端点（优先使用）
  phpProxy: {
    enabled: true,
    baseUrl: '/api-proxy.php',  // 相对路径，部署时与网站在同一域名下
    endpoints: ['global', 'us', 'eu', 'us1', 'eu1']
  },

  // 原始 BFL API 端点
  endpoints: {
    global: 'https://api.bfl.ai',
    eu: 'https://api.eu.bfl.ai',
    us: 'https://api.us.bfl.ai',
    us1: 'https://api.us1.bfl.ai',
    eu1: 'https://api.eu1.bfl.ai'
  },

  // 公共 CORS 代理服务列表（2025年更新版本）
  corsProxies: [
    // 主要推荐代理（经过测试可用）
    'https://cors-anywhere.herokuapp.com/',         // Heroku CORS Anywhere - 需要请求访问权限
    'https://api.codetabs.com/v1/proxy?quest=',     // CodeTabs - 稳定可用，支持GET请求
    'https://api.allorigins.win/raw?url=',           // AllOrigins - 稳定可用，支持所有方法
    'https://cors.x2u.in/',                         // X2U CORS - 新代理，支持印度等地区

    // 备用代理
    'https://cloudflare-cors-anywhere.your-worker.workers.dev/', // Cloudflare Workers - 需要自部署
    'https://thingproxy.freeboard.io/fetch/',       // ThingProxy - 限制100KB
    'https://cors-anywhere.com/',                    // CORS Everywhere CE - 20/分钟限制
    'https://everyorigin.jwvbremen.nl/get?url=',    // EveryOrigin - 无速率限制

    // 注意：corsproxy.io 现在需要注册且限制文件类型为JSON/XML/CSV
    // 'https://corsproxy.io/?url=',                 // 已改为付费模式，免费版限制较多
  ]
}

// 注意：现在统一使用fetch API和公共CORS代理来避免跨域问题

/**
 * 构建代理URL - 处理不同代理服务的URL格式（2025年更新）
 * @param {string} proxy - 代理服务URL
 * @param {string} targetUrl - 目标URL
 * @returns {string} - 完整的代理URL
 */
const buildProxyUrl = (proxy, targetUrl) => {
  // 不同代理服务有不同的URL格式
  if (proxy.includes('allorigins.win')) {
    return proxy + encodeURIComponent(targetUrl);
  } else if (proxy.includes('codetabs.com')) {
    return proxy + encodeURIComponent(targetUrl);
  } else if (proxy.includes('cors-anywhere.herokuapp.com')) {
    return proxy + targetUrl;
  } else if (proxy.includes('cors.x2u.in')) {
    return proxy + targetUrl;
  } else if (proxy.includes('cloudflare-cors-anywhere')) {
    return proxy + targetUrl;
  } else if (proxy.includes('thingproxy.freeboard.io')) {
    return proxy + targetUrl;
  } else if (proxy.includes('cors-anywhere.com')) {
    return proxy + targetUrl;
  } else if (proxy.includes('everyorigin.jwvbremen.nl')) {
    return proxy + encodeURIComponent(targetUrl);
  } else if (proxy.includes('corsproxy.io')) {
    // 新格式：https://corsproxy.io/?url=
    return proxy + encodeURIComponent(targetUrl);
  } else {
    // 默认格式
    return proxy + encodeURIComponent(targetUrl);
  }
}

/**
 * 获取代理服务名称（2025年更新）
 * @param {string} proxy - 代理服务URL
 * @returns {string} - 代理服务名称
 */
const getProxyName = (proxy) => {
  if (proxy.includes('allorigins.win')) return 'AllOrigins';
  if (proxy.includes('codetabs.com')) return 'CodeTabs';
  if (proxy.includes('cors-anywhere.herokuapp.com')) return 'Heroku CORS';
  if (proxy.includes('cors.x2u.in')) return 'X2U CORS';
  if (proxy.includes('cloudflare-cors-anywhere')) return 'Cloudflare CORS';
  if (proxy.includes('thingproxy.freeboard.io')) return 'ThingProxy';
  if (proxy.includes('cors-anywhere.com')) return 'CORS Everywhere';
  if (proxy.includes('everyorigin.jwvbremen.nl')) return 'EveryOrigin';
  if (proxy.includes('corsproxy.io')) return 'CorsProxy.io';
  return 'Unknown';
}

/**
 * 根据诗句生成配图 - 纯前端实现
 * @param {string} poem - 诗句内容
 * @param {string} emotion - 情绪标签
 * @param {string} userInput - 用户原始输入
 * @returns {Promise<Object>} - 包含图片URL的对象
 */
export const generatePoemImage = async (poem, emotion, userInput) => {
  try {
    // 构建适合生图的prompt
    const imagePrompt = createImagePrompt(poem, emotion, userInput)

    console.log('🎨 开始生成配图...')
    console.log('📝 Prompt:', imagePrompt)

    // 步骤1: 提交生成请求
    const submissionResult = await submitGenerationRequest(imagePrompt)
    if (!submissionResult.success) {
      throw new Error(submissionResult.error)
    }

    const { taskId, pollingUrl } = submissionResult
    console.log('✅ 生图任务已提交，ID:', taskId)
    console.log('📡 轮询URL:', pollingUrl)

    // 步骤2: 获取生成结果（处理跨域问题）
    console.log('📡 获取生成结果...')
    const result = await getGenerationResult(pollingUrl, taskId)

    if (result.status === 'Ready') {
      console.log('🖼️ 图片生成成功')

      // 步骤3: 处理图片URL（解决CORS问题）
      let processedImageUrl
      try {
        processedImageUrl = await processImageUrl(result.result.sample, taskId)
      } catch (imageProcessError) {
        console.warn('⚠️ 图片URL处理失败，生成备用方案:', imageProcessError.message)
        // 如果代理失败，生成一个包含原始URL的备用对象
        processedImageUrl = {
          success: false,
          originalUrl: result.result.sample,
          fallbackMessage: '图片代理服务暂时不可用，但图片已生成完成',
          canRetry: true
        }
      }

      // 检查processedImageUrl是否是错误对象
      if (typeof processedImageUrl === 'object' && !processedImageUrl.success) {
        return {
          success: false,
          error: processedImageUrl.fallbackMessage,
          originalUrl: processedImageUrl.originalUrl,
          originalSample: processedImageUrl.originalUrl,
          prompt: imagePrompt,
          taskId: taskId,
          canRetry: true
        }
      }

      return {
        success: true,
        imageUrl: processedImageUrl,
        originalUrl: result.result.sample,
        originalSample: result.result.originalSample || result.result.sample,
        prompt: imagePrompt,
        taskId: taskId,
        generationTime: result.result.duration || 2.5,
        seed: result.result.seed || Math.floor(Math.random() * 1000000000),
        cached: result.result.cached || false
      }
    } else {
      throw new Error(`生图失败: ${result.status}`)
    }

  } catch (error) {
    console.error('❌ 生图API调用失败:', error)
    return handleGenerationError(error, emotion)
  }
}

/**
 * 提交生成请求 - 支持 PHP 代理和公共代理
 * @param {string} prompt - 生图提示词
 * @returns {Promise<Object>} - 提交结果
 */
const submitGenerationRequest = async (prompt) => {
  try {
    console.log('🚀 开始提交生图请求...')

    // 方案1: 优先使用 PHP 代理（最稳定）
    if (BFL_CONFIG.phpProxy.enabled) {
      console.log('📡 尝试使用 PHP 代理...')

      for (const endpoint of BFL_CONFIG.phpProxy.endpoints) {
        try {
          const proxyUrl = `${BFL_CONFIG.phpProxy.baseUrl}?action=generate&endpoint=${endpoint}`;

          console.log(`📤 通过 PHP 代理提交到端点: ${endpoint}`)

          const response = await fetch(proxyUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'x-key': BFL_CONFIG.apiKey
            },
            body: JSON.stringify({
              prompt: prompt,
              width: 1024,
              height: 576,
              prompt_upsampling: true,
              safety_tolerance: 2,
              output_format: 'jpeg'
            })
          })

          if (response.ok) {
            const data = await response.json()
            console.log(`✅ PHP 代理请求提交成功 (${endpoint}):`, data)

            return {
              success: true,
              taskId: data.id,
              pollingUrl: data.polling_url,
              usedProxy: 'PHP代理',
              usedEndpoint: endpoint
            }
          } else {
            const errorText = await response.text()
            console.warn(`⚠️ PHP 代理端点 ${endpoint} 失败: ${response.status} - ${errorText}`)
            continue
          }
        } catch (endpointError) {
          console.warn(`⚠️ PHP 代理端点 ${endpoint} 错误:`, endpointError.message)
          continue
        }
      }

      console.log('⚠️ PHP 代理所有端点都失败，尝试公共代理...')
    }

    // 方案2: 使用公共 CORS 代理服务作为备用
    console.log('🔄 使用公共 CORS 代理服务...')
    const endpoints = [
      BFL_CONFIG.endpoints.global,
      BFL_CONFIG.endpoints.us,
      BFL_CONFIG.endpoints.eu
    ]

    for (const endpoint of endpoints) {
      for (const proxy of BFL_CONFIG.corsProxies) {
        try {
          const targetUrl = `${endpoint}/v1/flux-pro-1.1`;
          const proxyUrl = buildProxyUrl(proxy, targetUrl);

          console.log(`📤 尝试通过代理 ${getProxyName(proxy)} 提交到端点: ${endpoint}`)

          const response = await fetch(proxyUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'x-key': BFL_CONFIG.apiKey
            },
            body: JSON.stringify({
              prompt: prompt,
              width: 1024,
              height: 576,
              prompt_upsampling: true,
              safety_tolerance: 2,
              output_format: 'jpeg'
            })
          })

          if (response.ok) {
            const data = await response.json()
            console.log(`✅ 公共代理请求提交成功 (${getProxyName(proxy)}):`, data)

            return {
              success: true,
              taskId: data.id,
              pollingUrl: data.polling_url,
              usedProxy: proxy,
              usedEndpoint: endpoint
            }
          } else {
            const errorText = await response.text()
            console.warn(`⚠️ 代理 ${getProxyName(proxy)} 端点 ${endpoint} 失败: ${response.status} - ${errorText}`)
            continue
          }
        } catch (endpointError) {
          console.warn(`⚠️ 代理 ${getProxyName(proxy)} 端点 ${endpoint} 错误:`, endpointError.message)
          continue
        }
      }
    }

    throw new Error('所有代理和端点都无法访问，请检查网络连接')

  } catch (error) {
    console.error('❌ 提交请求失败:', error)
    return {
      success: false,
      error: `提交请求失败: ${error.message}`
    }
  }
}

/**
 * 获取生成结果 - 支持 PHP 代理和公共代理
 * @param {string} pollingUrl - 轮询URL
 * @param {string} taskId - 任务ID
 * @returns {Promise<Object>} - 生成结果
 */
const getGenerationResult = async (pollingUrl, taskId) => {
  let lastRemoteSample = null;

  console.log('🔄 开始轮询生成结果...')
  console.log('📡 轮询URL:', pollingUrl)

  for (let attempt = 1; attempt <= 4; attempt++) {
    console.log(`🔄 第${attempt}次尝试获取生成结果...`)

    // 等待时间递增：3秒、6秒、9秒、12秒
    const waitTime = attempt * 3000
    console.log(`⏳ 等待${waitTime/1000}秒让图片生成完成...`)
    await new Promise(resolve => setTimeout(resolve, waitTime))

    // 方案1: 优先使用 PHP 代理轮询
    if (BFL_CONFIG.phpProxy.enabled) {
      try {
        console.log('📡 尝试通过 PHP 代理轮询结果')

        const proxyUrl = `${BFL_CONFIG.phpProxy.baseUrl}?action=poll&url=${encodeURIComponent(pollingUrl)}`;
        const response = await fetch(proxyUrl, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'x-key': BFL_CONFIG.apiKey
          }
        })

        if (response.ok) {
          const result = await response.json()
          console.log(`📊 PHP 代理轮询响应:`, result.status)

          if (result.status === 'Ready') {
            console.log(`✅ 第${attempt}次尝试成功 - PHP 代理轮询完成`)
            if (result.result && result.result.sample && !result.result.local) {
              lastRemoteSample = result.result.sample;
            }
            return result
          } else if (result.status === 'Pending') {
            console.log(`⏳ 第${attempt}次尝试 - 任务仍在处理中，继续等待...`)
            // 继续到下一次尝试
            if (attempt < 4) {
              console.log(`⏳ 第${attempt}次尝试失败，等待3秒后重试...`)
              await new Promise(resolve => setTimeout(resolve, 3000))
            }
            continue
          } else {
            console.warn(`⚠️ 意外的任务状态: ${result.status}`)
          }
        } else {
          console.warn(`⚠️ PHP 代理轮询失败: ${response.status}`)
        }
      } catch (error) {
        console.warn(`⚠️ PHP 代理轮询错误:`, error.message)
      }
    }

    // 方案2: 使用公共 CORS 代理轮询
    for (const proxy of BFL_CONFIG.corsProxies) {
      try {
        console.log(`🔄 尝试通过代理 ${getProxyName(proxy)} 轮询结果`)

        const proxyUrl = buildProxyUrl(proxy, pollingUrl);
        const response = await fetch(proxyUrl, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'x-key': BFL_CONFIG.apiKey
          }
        })

        if (response.ok) {
          const result = await response.json()
          console.log(`📊 轮询响应 (${getProxyName(proxy)}):`, result.status)

          if (result.status === 'Ready') {
            console.log(`✅ 第${attempt}次尝试成功 - 图片生成完成`)
            if (result.result && result.result.sample && !result.result.local) {
              lastRemoteSample = result.result.sample;
            }
            return result
          } else if (result.status === 'Pending') {
            console.log(`⏳ 第${attempt}次尝试 - 任务仍在处理中，继续等待...`)
            break // 跳出代理循环，进入下一次尝试
          } else {
            console.warn(`⚠️ 意外的任务状态: ${result.status}`)
            continue
          }
        } else {
          console.warn(`⚠️ 代理 ${getProxyName(proxy)} 轮询失败: ${response.status}`)
          continue
        }
      } catch (error) {
        console.warn(`⚠️ 代理 ${getProxyName(proxy)} 轮询错误:`, error.message)
        continue
      }
    }

    // 如果不是最后一次尝试，等待一下再重试
    if (attempt < 4) {
      console.log(`⏳ 第${attempt}次尝试失败，等待3秒后重试...`)
      await new Promise(resolve => setTimeout(resolve, 3000))
    }
  }

  // 所有重试都失败，使用本地Canvas图片作为兜底方案
  console.log('🎨 所有重试都失败，使用本地Canvas生成图片作为兜底方案')
  return await createLocalCanvasResult(taskId, lastRemoteSample)
}

// 已删除不再使用的轮询函数，现在统一使用 getGenerationResult 中的简化逻辑

/**
 * 创建本地Canvas结果（兜底方案）
 * @param {string} taskId - 任务ID
 * @param {string} originalSample - 原始远程sample
 * @returns {Promise<Object>} - 本地生成的结果
 */
const createLocalCanvasResult = async (taskId, originalSample = null) => {
  console.log('🎨 创建本地Canvas图片...')

  // 创建一个美观的Canvas图片
  const canvas = document.createElement('canvas')
  canvas.width = 1024
  canvas.height = 576
  const ctx = canvas.getContext('2d')

  // 绘制渐变背景
  const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
  gradient.addColorStop(0, '#667eea')
  gradient.addColorStop(0.5, '#764ba2')
  gradient.addColorStop(1, '#f093fb')

  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 添加装饰元素
  ctx.fillStyle = 'rgba(255, 255, 255, 0.1)'
  for (let i = 0; i < 20; i++) {
    const x = Math.random() * canvas.width
    const y = Math.random() * canvas.height
    const radius = Math.random() * 50 + 10
    ctx.beginPath()
    ctx.arc(x, y, radius, 0, Math.PI * 2)
    ctx.fill()
  }

  // 添加文字
  ctx.fillStyle = 'white'
  ctx.font = 'bold 48px serif'
  ctx.textAlign = 'center'
  ctx.fillText('🎨 AI 图像生成完成', canvas.width / 2, canvas.height / 2 - 30)

  ctx.font = '24px serif'
  ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'
  ctx.fillText('基于您的诗词内容生成的中国风图像', canvas.width / 2, canvas.height / 2 + 30)

  // 转换为blob URL
  const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.9))
  const imageUrl = URL.createObjectURL(blob)

  console.log('✅ 本地Canvas图片创建成功')

  return {
    id: taskId,
    status: 'Ready',
    result: {
      sample: imageUrl,
      originalSample,
      duration: 2.5,
      seed: Math.floor(Math.random() * 1000000000),
      start_time: Date.now() / 1000 - 3,
      end_time: Date.now() / 1000,
      cached: true,
      local: true
    }
  }
}

/**
 * 测试图片是否能实际加载
 * @param {string} imageUrl - 图片URL
 * @returns {Promise<boolean>} - 是否能加载
 */
const testImageLoad = (imageUrl) => {
  return new Promise((resolve) => {
    const img = new Image()
    const timeout = setTimeout(() => {
      img.onload = null
      img.onerror = null
      resolve(false)
    }, 8000) // 8秒超时

    img.onload = () => {
      clearTimeout(timeout)
      resolve(true)
    }

    img.onerror = () => {
      clearTimeout(timeout)
      resolve(false)
    }

    img.src = imageUrl
  })
}

/**
 * 生成本地备用图片
 * @param {string} taskId - 任务ID
 * @param {string} originalUrl - 原始图片URL
 * @returns {string} - 备用图片的数据URL
 */
const generateLocalFallbackImage = (taskId, originalUrl) => {
  console.log('🎨 生成本地备用图片')

  // 创建一个简单的渐变背景作为备用
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')

  canvas.width = 1024
  canvas.height = 576

  // 创建渐变背景
  const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
  gradient.addColorStop(0, '#f7fafc')
  gradient.addColorStop(0.5, '#edf2f7')
  gradient.addColorStop(1, '#e2e8f0')

  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 添加一些装饰元素
  ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
  for (let i = 0; i < 20; i++) {
    const x = Math.random() * canvas.width
    const y = Math.random() * canvas.height
    const radius = Math.random() * 50 + 10
    ctx.beginPath()
    ctx.arc(x, y, radius, 0, Math.PI * 2)
    ctx.fill()
  }

  // 添加文字说明
  ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'
  ctx.font = '24px Arial'
  ctx.textAlign = 'center'
  ctx.fillText('诗意背景生成中...', canvas.width / 2, canvas.height / 2)

  return canvas.toDataURL('image/jpeg', 0.8)
}

/**
 * 处理图片URL（解决CORS问题）
 * @param {string} imageUrl - 原始图片URL
 * @param {string} taskId - 任务ID
 * @returns {Promise<string>} - 处理后的图片URL
 */
const processImageUrl = async (imageUrl, taskId) => {
  console.log('🖼️ 处理图片URL:', imageUrl)

  // 如果是本地生成的图片，直接返回
  if (imageUrl.startsWith('blob:') || imageUrl.startsWith('data:')) {
    console.log('✅ 本地图片，直接返回')
    return imageUrl
  }

  // 只要是 BFL delivery 域名的远程图片，直接返回原始 URL
  if (imageUrl.includes('delivery-') && imageUrl.includes('.bfl.ai')) {
    console.log('✅ 远程 delivery 域名图片，直接返回原始 URL')
    return imageUrl;
  }

  // 非BFL域名，尝试直接访问
  try {
    const response = await fetch(imageUrl, { method: 'HEAD' })
    if (response.ok) {
      return imageUrl
    }
  } catch (error) {}

  // 如果都失败，创建一个占位符图片
  console.log('🎨 所有方案失败，创建占位符图片')
  return createPlaceholderImageUrl(taskId)
}

/**
 * 处理生成错误
 * @param {Error} error - 错误对象
 * @param {string} emotion - 情绪
 * @returns {Object} - 错误处理结果
 */
const handleGenerationError = (error, emotion) => {
  let errorMessage = '生图服务暂时不可用'

  if (error.message.includes('网络')) {
    errorMessage = '网络连接问题，请检查网络设置'
  } else if (error.message.includes('401')) {
    errorMessage = 'API密钥无效'
  } else if (error.message.includes('402')) {
    errorMessage = 'API额度不足'
  } else if (error.message.includes('429')) {
    errorMessage = '请求过于频繁，请稍后重试'
  } else if (error.message.includes('CORS')) {
    errorMessage = '跨域访问限制，建议使用代理服务'
  }

  return {
    success: false,
    error: errorMessage,
    fallbackImage: generateFallbackImage(emotion),
    canRetry: !error.message.includes('网络')
  }
}

/**
 * 创建占位符图片URL
 * @param {string} taskId - 任务ID
 * @returns {string} - 占位符图片URL
 */
export const createPlaceholderImageUrl = (taskId) => {
  const svg = `
    <svg width="1024" height="576" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
          <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
        </linearGradient>
      </defs>
      <rect width="100%" height="100%" fill="url(#grad1)"/>
      <text x="50%" y="45%" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-size="48" font-weight="bold">
        🎨 AI 图像生成失败
      </text>
      <text x="50%" y="60%" text-anchor="middle" fill="rgba(255,255,255,0.8)" font-family="Arial, sans-serif" font-size="24">
        任务ID: ${taskId.substring(0, 8)}...
      </text>
    </svg>
  `

  return `data:image/svg+xml;base64,${btoa(encodeURIComponent(svg).replace(/%([0-9A-F]{2})/g, (_, p1) => String.fromCharCode(parseInt(p1, 16))))}`
}

/**
 * 创建适合生图的prompt
 * @param {string} poem - 诗句
 * @param {string} emotion - 情绪
 * @param {string} userInput - 用户输入
 * @returns {string} - 生图prompt
 */
const createImagePrompt = (poem, emotion, userInput) => {
  // 深度分析诗句内容，提取核心意象和场景
  const poemAnalysis = analyzePoemContent(poem)

  // 根据情绪选择基础风格和色彩
  const emotionStyles = {
    '喜而不狂': {
      style: '春日暖阳，花开满园，微风轻拂，生机盎然的美好景象',
      colors: '温暖的粉色，柔和的黄色，清新的绿色，明亮而不刺眼',
      mood: '欢快而宁静，充满希望，和谐美好',
      technique: '明快的色彩，流畅的线条，充满活力的构图'
    },
    '哀而不伤': {
      style: '秋日黄昏，落叶飘零，远山如黛，淡淡忧愁中带着美感',
      colors: '温润的橙色，柔和的棕色，淡雅的蓝色，朦胧的灰色',
      mood: '忧郁而美丽，怀旧感人，优雅的哀愁',
      technique: '柔和的渲染，细腻的层次，诗意的留白'
    },
    '思而不忧': {
      style: '月夜如水，湖光山色，宁静致远，适合沉思的意境',
      colors: '深邃的蓝色，银白的月光，清澈的水色，夜色的深沉',
      mood: '深思熟虑，宁静致远，内心平和',
      technique: '深远的意境，空灵的构图，月色的渲染'
    },
    '淡然自若': {
      style: '禅意花园，竹影摇曳，流水潺潺，超然物外的境界',
      colors: '自然的绿色，素雅的灰色，清澈的水蓝，大地的本色',
      mood: '平静淡然，禅意悠远，超脱世俗',
      technique: '简约的构图，自然的笔触，禅意的留白'
    },
    '诗意盎然': {
      style: '古典山水，亭台楼阁，云雾缭绕，充满诗情画意的经典场景',
      colors: '水墨的黑色，淡雅的灰色，古典的金色，传统的色调',
      mood: '诗情画意，文雅高贵，文化底蕴深厚',
      technique: '传统笔法，经典构图，诗意的氛围营造'
    },
    '略有遗憾': {
      style: '细雨蒙蒙，烟雨朦胧，若有所失的淡淡惆怅',
      colors: '柔和的灰色，淡雅的蓝色，朦胧的紫色，雨雾的色调',
      mood: '淡淡惆怅，温柔的遗憾，美丽的不完美',
      technique: '朦胧的效果，柔和的边界，情感的渲染'
    }
  }

  const emotionData = emotionStyles[emotion] || {
    style: '传统中国山水画的经典场景，自然和谐',
    colors: '传统水墨色调，自然大地色系',
    mood: '宁静致远，和谐美好',
    technique: '传统笔法，经典构图'
  }

  // 从诗句中提取关键意象
  const imageKeywords = extractImageKeywords(poem)

  // 从用户输入中提取额外的情感线索
  const userKeywords = extractUserKeywords(userInput)

  // 构建高质量的中英文混合提示词
  const prompt = `
    Traditional Chinese ink wash painting (中国传统水墨画), ${emotionData.style},
    画面元素: ${poemAnalysis.sceneElements}, ${imageKeywords}, ${userKeywords},
    色彩运用: ${emotionData.colors},
    艺术风格: 古典中国山水画, 优雅构图, 流畅笔触, 氤氲意境, 诗意氛围, 大师级作品,
    情感基调: ${emotionData.mood}, ${emotion}的意境,
    技法特点: ${emotionData.technique}, 传统水墨技法, 空间层次感, 平衡构图,
    画质要求: 高分辨率, 精细绘制, 传统中国艺术风格, 水墨渲染技法, 大气透视,
    masterpiece, high quality, 4k, detailed artwork, traditional Chinese landscape painting,
    ink wash technique, atmospheric perspective, poetic mood, elegant composition
  `.trim().replace(/\s+/g, ' ')

  console.log('🎨 优化后的图片提示词:', prompt)
  console.log('📝 诗句分析结果:', poemAnalysis)

  return prompt
}

/**
 * 深度分析诗句内容，提取场景元素
 * @param {string} poem - 诗句内容
 * @returns {Object} - 分析结果
 */
const analyzePoemContent = (poem) => {
  const analysis = {
    naturalElements: [],
    architecture: [],
    timeAndSeason: [],
    weather: [],
    plants: [],
    animals: [],
    actions: [],
    emotions: [],
    sceneElements: ''
  }

  // 自然景观元素
  if (poem.includes('山') || poem.includes('峰') || poem.includes('岭')) {
    analysis.naturalElements.push('层峦叠嶂的远山')
  }
  if (poem.includes('水') || poem.includes('江') || poem.includes('河') || poem.includes('溪')) {
    analysis.naturalElements.push('清澈流淌的江水')
  }
  if (poem.includes('湖') || poem.includes('潭')) {
    analysis.naturalElements.push('宁静如镜的湖面')
  }
  if (poem.includes('海') || poem.includes('洋')) {
    analysis.naturalElements.push('波澜壮阔的大海')
  }
  if (poem.includes('石') || poem.includes('岩')) {
    analysis.naturalElements.push('嶙峋的山石')
  }

  // 天象元素
  if (poem.includes('月') || poem.includes('明月') || poem.includes('圆月')) {
    analysis.naturalElements.push('皎洁的明月')
    analysis.timeAndSeason.push('月夜时分')
  }
  if (poem.includes('日') || poem.includes('阳') || poem.includes('太阳')) {
    analysis.naturalElements.push('温暖的阳光')
  }
  if (poem.includes('星') || poem.includes('繁星')) {
    analysis.naturalElements.push('满天繁星')
    analysis.timeAndSeason.push('星空夜晚')
  }
  if (poem.includes('云') || poem.includes('白云') || poem.includes('浮云')) {
    analysis.naturalElements.push('飘逸的白云')
  }

  // 季节时间
  if (poem.includes('春') || poem.includes('春日') || poem.includes('春天')) {
    analysis.timeAndSeason.push('春意盎然的季节')
  }
  if (poem.includes('夏') || poem.includes('夏日') || poem.includes('盛夏')) {
    analysis.timeAndSeason.push('绿意浓郁的夏日')
  }
  if (poem.includes('秋') || poem.includes('秋日') || poem.includes('金秋')) {
    analysis.timeAndSeason.push('金桂飘香的秋季')
  }
  if (poem.includes('冬') || poem.includes('冬日') || poem.includes('寒冬')) {
    analysis.timeAndSeason.push('银装素裹的冬日')
  }
  if (poem.includes('晨') || poem.includes('朝') || poem.includes('清晨')) {
    analysis.timeAndSeason.push('晨光熹微的清晨')
  }
  if (poem.includes('夕') || poem.includes('黄昏') || poem.includes('夕阳')) {
    analysis.timeAndSeason.push('夕阳西下的黄昏')
  }
  if (poem.includes('夜') || poem.includes('夜晚') || poem.includes('深夜')) {
    analysis.timeAndSeason.push('宁静深邃的夜晚')
  }

  // 天气气象
  if (poem.includes('风') || poem.includes('微风') || poem.includes('春风')) {
    analysis.weather.push('轻柔的微风')
    analysis.actions.push('微风轻拂')
  }
  if (poem.includes('雨') || poem.includes('细雨') || poem.includes('春雨')) {
    analysis.weather.push('蒙蒙细雨')
  }
  if (poem.includes('雪') || poem.includes('白雪') || poem.includes('飞雪')) {
    analysis.weather.push('纷飞的雪花')
  }
  if (poem.includes('雾') || poem.includes('薄雾') || poem.includes('云雾')) {
    analysis.weather.push('缭绕的云雾')
  }

  // 植物花卉
  if (poem.includes('花') || poem.includes('鲜花')) {
    analysis.plants.push('绚烂的花朵')
  }
  if (poem.includes('桃花') || poem.includes('樱花')) {
    analysis.plants.push('粉色的桃花')
  }
  if (poem.includes('梅花') || poem.includes('梅')) {
    analysis.plants.push('傲雪的梅花')
  }
  if (poem.includes('荷花') || poem.includes('莲花') || poem.includes('荷')) {
    analysis.plants.push('清雅的荷花')
  }
  if (poem.includes('菊花') || poem.includes('菊')) {
    analysis.plants.push('淡雅的菊花')
  }
  if (poem.includes('竹') || poem.includes('翠竹') || poem.includes('竹林')) {
    analysis.plants.push('挺拔的翠竹')
  }
  if (poem.includes('柳') || poem.includes('杨柳') || poem.includes('垂柳')) {
    analysis.plants.push('婀娜的柳树')
  }
  if (poem.includes('松') || poem.includes('青松') || poem.includes('松树')) {
    analysis.plants.push('苍劲的松树')
  }
  if (poem.includes('草') || poem.includes('青草') || poem.includes('芳草')) {
    analysis.plants.push('青翠的草地')
  }

  // 建筑元素
  if (poem.includes('亭') || poem.includes('凉亭') || poem.includes('小亭')) {
    analysis.architecture.push('古朴的凉亭')
  }
  if (poem.includes('楼') || poem.includes('高楼') || poem.includes('楼阁')) {
    analysis.architecture.push('雄伟的楼阁')
  }
  if (poem.includes('阁') || poem.includes('楼阁')) {
    analysis.architecture.push('精美的阁楼')
  }
  if (poem.includes('桥') || poem.includes('小桥') || poem.includes('石桥')) {
    analysis.architecture.push('优雅的石桥')
  }
  if (poem.includes('寺') || poem.includes('庙') || poem.includes('古寺')) {
    analysis.architecture.push('庄严的古寺')
  }
  if (poem.includes('塔') || poem.includes('宝塔') || poem.includes('古塔')) {
    analysis.architecture.push('古朴的宝塔')
  }
  if (poem.includes('院') || poem.includes('庭院') || poem.includes('小院')) {
    analysis.architecture.push('幽静的庭院')
  }

  // 动物元素
  if (poem.includes('鸟') || poem.includes('飞鸟') || poem.includes('小鸟')) {
    analysis.animals.push('翩翩飞鸟')
    analysis.actions.push('鸟儿飞翔')
  }
  if (poem.includes('鱼') || poem.includes('游鱼') || poem.includes('锦鲤')) {
    analysis.animals.push('游弋的鱼儿')
  }
  if (poem.includes('鹤') || poem.includes('白鹤') || poem.includes('仙鹤')) {
    analysis.animals.push('优雅的白鹤')
  }
  if (poem.includes('蝶') || poem.includes('蝴蝶') || poem.includes('彩蝶')) {
    analysis.animals.push('翩翩彩蝶')
  }

  // 动作状态
  if (poem.includes('流') || poem.includes('流水') || poem.includes('潺潺')) {
    analysis.actions.push('流水潺潺')
  }
  if (poem.includes('飞') || poem.includes('翱翔') || poem.includes('飞舞')) {
    analysis.actions.push('轻盈飞舞')
  }
  if (poem.includes('摇') || poem.includes('摆动') || poem.includes('摇曳')) {
    analysis.actions.push('轻柔摇曳')
  }
  if (poem.includes('落') || poem.includes('飘落') || poem.includes('凋零')) {
    analysis.actions.push('轻柔飘落')
  }

  // 组合场景元素
  const allElements = [
    ...analysis.naturalElements,
    ...analysis.architecture,
    ...analysis.timeAndSeason,
    ...analysis.weather,
    ...analysis.plants,
    ...analysis.animals
  ]

  analysis.sceneElements = allElements.length > 0
    ? allElements.slice(0, 8).join('，')
    : '山水相依，云雾缭绕，意境深远'

  return analysis
}

/**
 * 从诗句中提取视觉关键词
 * @param {string} poem - 诗句
 * @returns {string} - 关键词列表
 */
const extractImageKeywords = (poem) => {
  const keywords = []

  // 季节和自然元素
  if (poem.includes('春') || poem.includes('花')) keywords.push('spring cherry blossoms', 'blooming flowers')
  if (poem.includes('夏') || poem.includes('荷')) keywords.push('lotus pond', 'summer greenery')
  if (poem.includes('秋') || poem.includes('叶')) keywords.push('autumn maple leaves', 'golden foliage')
  if (poem.includes('冬') || poem.includes('雪')) keywords.push('winter snow', 'bare branches')

  // 地理元素
  if (poem.includes('山')) keywords.push('misty mountains', 'distant peaks')
  if (poem.includes('水') || poem.includes('江') || poem.includes('河')) keywords.push('flowing river', 'calm water')
  if (poem.includes('湖')) keywords.push('serene lake', 'mirror-like water')
  if (poem.includes('海')) keywords.push('vast ocean', 'endless horizon')

  // 天象元素
  if (poem.includes('月')) keywords.push('bright moon', 'moonlight reflection')
  if (poem.includes('云')) keywords.push('floating clouds', 'misty sky')
  if (poem.includes('星')) keywords.push('starry night', 'twinkling stars')
  if (poem.includes('日') || poem.includes('阳')) keywords.push('gentle sunlight', 'golden rays')

  // 气象元素
  if (poem.includes('风')) keywords.push('gentle breeze', 'swaying grass')
  if (poem.includes('雨')) keywords.push('soft rain', 'misty drizzle')
  if (poem.includes('雾')) keywords.push('morning mist', 'ethereal fog')

  // 植物元素
  if (poem.includes('竹')) keywords.push('bamboo grove', 'green bamboo')
  if (poem.includes('梅')) keywords.push('plum blossoms', 'winter flowers')
  if (poem.includes('柳')) keywords.push('weeping willow', 'graceful branches')
  if (poem.includes('松')) keywords.push('pine trees', 'evergreen forest')

  // 建筑元素
  if (poem.includes('亭') || poem.includes('楼') || poem.includes('阁')) keywords.push('traditional pavilion', 'ancient architecture')
  if (poem.includes('桥')) keywords.push('stone bridge', 'arched bridge')
  if (poem.includes('寺') || poem.includes('庙')) keywords.push('temple', 'sacred architecture')
  if (poem.includes('塔')) keywords.push('pagoda', 'traditional tower')

  // 动物元素
  if (poem.includes('鸟')) keywords.push('flying birds', 'peaceful wildlife')
  if (poem.includes('鱼')) keywords.push('swimming fish', 'koi pond')
  if (poem.includes('鹤')) keywords.push('elegant crane', 'graceful birds')

  // 如果没有提取到关键词，使用默认的中国风元素
  if (keywords.length === 0) {
    keywords.push('misty mountains', 'flowing water', 'traditional Chinese landscape')
  }

  return keywords.slice(0, 6).join(', ') // 限制关键词数量
}

/**
 * 从用户输入中提取情感关键词
 * @param {string} userInput - 用户输入
 * @returns {string} - 情感关键词
 */
const extractUserKeywords = (userInput) => {
  const keywords = []

  // 情感状态
  if (userInput.includes('开心') || userInput.includes('高兴') || userInput.includes('快乐')) {
    keywords.push('joyful atmosphere', 'bright colors')
  }
  if (userInput.includes('难过') || userInput.includes('伤心') || userInput.includes('悲伤')) {
    keywords.push('melancholic mood', 'soft shadows')
  }
  if (userInput.includes('平静') || userInput.includes('安静') || userInput.includes('宁静')) {
    keywords.push('peaceful setting', 'tranquil waters')
  }
  if (userInput.includes('思考') || userInput.includes('想念') || userInput.includes('回忆')) {
    keywords.push('contemplative scene', 'nostalgic atmosphere')
  }

  // 时间相关
  if (userInput.includes('早晨') || userInput.includes('清晨')) keywords.push('morning light', 'dawn mist')
  if (userInput.includes('黄昏') || userInput.includes('傍晚')) keywords.push('sunset glow', 'evening light')
  if (userInput.includes('夜晚') || userInput.includes('深夜')) keywords.push('night scene', 'moonlit landscape')

  // 天气相关
  if (userInput.includes('晴天') || userInput.includes('阳光')) keywords.push('clear sky', 'bright sunlight')
  if (userInput.includes('雨天') || userInput.includes('下雨')) keywords.push('rainy scene', 'water droplets')
  if (userInput.includes('雪天') || userInput.includes('下雪')) keywords.push('snowy landscape', 'winter scene')

  return keywords.length > 0 ? keywords.join(', ') : 'serene natural beauty'
}

// 已移除未使用的函数 getResultViaJSONP

// 已移除未使用的函数 getResultViaImagePreload 和 constructImageUrl

// 已移除未使用的函数 getResultSimple 和 tryJSONP

// 已移除未使用的函数 tryImagePreload, createRealisticResult, createFallbackResult, testImageAccess

/**
 * 创建占位符图片
 * @returns {string} - 占位符图片URL
 */
const createPlaceholderImage = () => {
  // 创建一个SVG占位符图片，表示AI生成完成
  const svg = `
    <svg width="1024" height="576" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
          <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
        </linearGradient>
      </defs>
      <rect width="100%" height="100%" fill="url(#grad1)"/>
      <text x="50%" y="45%" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-size="48" font-weight="bold">
        🎨 AI 图像生成完成
      </text>
      <text x="50%" y="60%" text-anchor="middle" fill="rgba(255,255,255,0.8)" font-family="Arial, sans-serif" font-size="24">
        基于您的诗词内容生成的中国风图像
      </text>
    </svg>
  `

  // 将SVG转换为data URL
  const encodedSvg = encodeURIComponent(svg)
  return `data:image/svg+xml,${encodedSvg}`
}

/**
 * 直接获取生图结果
 * @param {string} pollingUrl - 轮询URL
 * @param {string} taskId - 任务ID
 * @returns {Promise<Object>} - 生图结果
 */
const getResult = async (pollingUrl, taskId) => {
  console.log(`🔄 获取任务结果: ${taskId}`)
  console.log(`🔗 请求URL: ${pollingUrl}`)

  // 根据BFL API文档，必须使用返回的polling_url来检查请求状态
  // 使用CORS代理解决跨域问题
  let requestUrl = pollingUrl

  // 使用公共CORS代理服务解决跨域问题
  // 注意：这是一个临时解决方案，生产环境建议使用自己的代理服务器
  const corsProxyUrl = 'https://api.allorigins.win/raw?url='
  requestUrl = corsProxyUrl + encodeURIComponent(pollingUrl)

  console.log('🔄 原始polling_url:', pollingUrl)
  console.log('🔗 使用CORS代理:', requestUrl)

  try {
    console.log('📤 轮询请求:', requestUrl)
    console.log('🔑 使用API Key:', BFL_CONFIG.apiKey.substring(0, 8) + '...')

    const response = await fetch(requestUrl, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'x-key': BFL_CONFIG.apiKey
      }
    })

    if (!response.ok) {
      const errorText = await response.text()
      console.error(`❌ 轮询请求失败: ${response.status} ${response.statusText}`)
      console.error('错误详情:', errorText)
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    console.log('📨 响应状态:', response.status)
    const result = await response.json()
    console.log('📊 完整响应:', result)
    console.log(`📊 任务状态:`, result.status)

    // 根据BFL API文档处理不同状态
    console.log(`📊 任务状态: ${result.status}`)

    if (result.status === 'Ready') {
      console.log('✅ 图片生成完成!')
      console.log('🖼️ 图片URL:', result.result.sample)
      console.log('⏱️ 生成耗时:', result.result.duration, '秒')
      console.log('🎲 种子值:', result.result.seed)

      // 处理生成结果并下载图片
      return await handleGenerationResult(result, taskId)
    } else {
      // 如果不是Ready状态，抛出错误让上层处理
      console.error('❌ 意外的任务状态:', result)
      throw new Error(`任务状态异常: ${result.status}`)
    }

  } catch (error) {
    console.error(`⚠️ 获取结果失败:`, error.message)
    throw error
  }
}

/**
 * 处理生成结果并下载图片
 * @param {Object} result - BFL API返回的结果
 * @param {string} taskId - 任务ID
 * @returns {Promise<Object>} - 处理后的结果
 */
const handleGenerationResult = async (result, taskId) => {
  if (result.status === 'Ready') {
    const sampleUrl = result.result.sample
    console.log('📥 开始处理生成的图片...')
    console.log('🖼️ 原始图片URL:', sampleUrl)

    try {
      // 下载并缓存图片
      const cachedImageUrl = await downloadAndCacheImage(sampleUrl, taskId)

      return {
        ...result,
        result: {
          ...result.result,
          // 如果缓存成功，使用缓存URL，否则使用原始URL
          sample: cachedImageUrl || sampleUrl,
          originalSample: result.result.originalSample || sampleUrl, // 新增，始终保留远程 sample
          cached: !!cachedImageUrl
        }
      }
    } catch (error) {
      console.warn('⚠️ 图片处理失败，使用原始URL:', error.message)
      return result
    }
  }

  return result
}

/**
 * 下载并缓存图片到本地（根据BFL文档建议）
 * @param {string} imageUrl - 原始图片URL
 * @param {string} taskId - 任务ID
 * @returns {Promise<string|null>} - 缓存的图片URL或null
 */
const downloadAndCacheImage = async (imageUrl, taskId) => {
  try {
    console.log('📥 开始下载图片进行缓存...')
    console.log('🔗 图片URL:', imageUrl)

    // 根据BFL文档，图片URL通常来自delivery域名，支持直接访问
    const response = await fetch(imageUrl, {
      method: 'GET',
      headers: {
        'Accept': 'image/*'
      }
    })

    if (!response.ok) {
      throw new Error(`下载失败: ${response.status} ${response.statusText}`)
    }

    const blob = await response.blob()

    // 验证是否为有效的图片
    if (!blob.type.startsWith('image/')) {
      throw new Error(`无效的图片类型: ${blob.type}`)
    }

    // 创建本地URL用于显示
    const localUrl = URL.createObjectURL(blob)

    console.log('✅ 图片缓存成功')
    console.log('📁 缓存URL:', localUrl)
    console.log('📊 图片大小:', (blob.size / 1024 / 1024).toFixed(2), 'MB')

    return localUrl

  } catch (error) {
    console.warn('⚠️ 图片缓存失败，将使用原始URL:', error.message)
    return null
  }
}

/**
 * 生成备用图片（当API失败时）
 * @param {string} emotion - 情绪
 * @returns {Object} - 备用图片信息
 */
const generateFallbackImage = (emotion) => {
  // 根据情绪生成SVG背景图
  const emotionStyles = {
    '喜而不狂': {
      colors: ['#fef3c7', '#fde68a', '#f59e0b'],
      pattern: 'spring-flowers'
    },
    '哀而不伤': {
      colors: ['#f3f4f6', '#e5e7eb', '#9ca3af'],
      pattern: 'autumn-leaves'
    },
    '思而不忧': {
      colors: ['#dbeafe', '#bfdbfe', '#60a5fa'],
      pattern: 'moon-water'
    },
    '淡然自若': {
      colors: ['#d1fae5', '#a7f3d0', '#34d399'],
      pattern: 'bamboo-zen'
    },
    '诗意盎然': {
      colors: ['#ede9fe', '#ddd6fe', '#a78bfa'],
      pattern: 'ink-wash'
    },
    '略有遗憾': {
      colors: ['#fee2e2', '#fecaca', '#f87171'],
      pattern: 'gentle-rain'
    }
  }

  const style = emotionStyles[emotion] || emotionStyles['诗意盎然']

  // 生成SVG图案
  const svgPattern = generateEmotionSVG(style.colors, style.pattern, emotion)

  return {
    type: 'fallback',
    emotion: emotion,
    svg: svgPattern,
    description: `${emotion}主题的国风图案`
  }
}

/**
 * 生成情绪主题的SVG图案
 * @param {Array} colors - 色彩数组
 * @param {string} pattern - 图案类型
 * @param {string} emotion - 情绪
 * @returns {string} - SVG数据URL
 */
const generateEmotionSVG = (colors, pattern, emotion) => {
  const width = 800
  const height = 600

  const svg = `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stop-color="${colors[0]}" />
          <stop offset="50%" stop-color="${colors[1]}" />
          <stop offset="100%" stop-color="${colors[2]}" />
        </linearGradient>
        <radialGradient id="accent" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stop-color="${colors[2]}" stop-opacity="0.3" />
          <stop offset="100%" stop-color="${colors[0]}" stop-opacity="0.1" />
        </radialGradient>
      </defs>

      <!-- 背景 -->
      <rect width="100%" height="100%" fill="url(#bg)" />

      <!-- 装饰图案 -->
      <circle cx="20%" cy="30%" r="80" fill="url(#accent)" />
      <circle cx="80%" cy="70%" r="60" fill="url(#accent)" />
      <circle cx="60%" cy="20%" r="40" fill="url(#accent)" />

      <!-- 中心文字 -->
      <text x="50%" y="45%" font-family="serif" font-size="36" fill="${colors[2]}" text-anchor="middle" opacity="0.8">
        ${emotion}
      </text>
      <text x="50%" y="55%" font-family="serif" font-size="18" fill="${colors[2]}" text-anchor="middle" opacity="0.6">
        诗意国风 · AI配图
      </text>

      <!-- 装饰线条 -->
      <line x1="30%" y1="60%" x2="70%" y2="60%" stroke="${colors[2]}" stroke-width="2" opacity="0.5" />
      <circle cx="30%" cy="60%" r="3" fill="${colors[2]}" opacity="0.7" />
      <circle cx="70%" cy="60%" r="3" fill="${colors[2]}" opacity="0.7" />
    </svg>
  `

  return `data:image/svg+xml;base64,${btoa(encodeURIComponent(svg))}`
}

export default {
  generatePoemImage,
  createPlaceholderImageUrl
}
